package tw.fatminmin.xposed.minminlock.util;

import android.app.WallpaperManager;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.AsyncTaskLoader;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.support.v4.app.LoaderManager;
import android.widget.ImageView;
import android.widget.Toast;

import java.lang.ref.SoftReference;

import tw.fatminmin.xposed.minminlock.R;

public class AndroidUtil {
    private static SoftReference<Drawable> WALLPAPER = new SoftReference<>(null);

    public static void getBackground(AppCompatActivity activity, final ImageView background){
        activity.getSupportLoaderManager().initLoader(0, null, new LoaderManager.LoaderCallbacks<Drawable>() {
            @Override
            public Loader<Drawable> onCreateLoader(int id, Bundle args) {
                return new AsyncTaskLoader<Drawable>(background.getContext()) {
                    @Override
                    protected void onStartLoading() {
                        super.onStartLoading();
                        forceLoad();
                    }

                    @Override
                    public Drawable loadInBackground() {
                        if (WALLPAPER.get() != null)
                            return WALLPAPER.get();
                        else
                            return WallpaperManager.getInstance(getContext()).getFastDrawable();
                    }
                };
            }

            @Override
            public void onLoadFinished(Loader<Drawable> loader, Drawable data) {
                if (data != null) {
                    background.setImageDrawable(data);
                    if (WALLPAPER.get() == null)
                        WALLPAPER = new SoftReference<>(data);
                } else {
                    background.setImageDrawable(new ColorDrawable(ContextCompat.getColor(background.getContext(), R.color.myWindowBackground)));
                    Toast.makeText(background.getContext(), "Failed to load system wallpaper!", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onLoaderReset(Loader<Drawable> loader) {
            }
        });
    }

    public static boolean isSystemApp(PackageInfo pInfo) {
        return ((pInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
    }

    public static boolean isSystemUpdateApp(PackageInfo pInfo) {
        return ((pInfo.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0);
    }

    public static boolean isUserApp(PackageInfo pInfo) {
        return (!isSystemApp(pInfo) && !isSystemUpdateApp(pInfo));
    }
}
